import { defineStore } from 'pinia'
import type { Conversation } from '@/types'
import {
  deleteConversation,
  getConversationById,
  getConversationList,
  renameConversation,
} from '@/api'
import { useUserStore } from './user'
import dayjs from 'dayjs'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
dayjs.extend(isSameOrAfter)

interface GroupedConversation {
  [key: string]: Conversation[]
}

export const useConversationStore = defineStore('conversation', {
  state: () => ({
    conversationList: [] as Conversation[],
    currentKey: '',
    // newConversationlist: [] as Conversation[],
    isAnswering: false,
    hasMore: false,
    lastId: '',
    loading: false,
    messageHasMore: false,
    messageFirstId: '',
  }),
  getters: {
    groupedConversation: (state): GroupedConversation => {
      const result: GroupedConversation = {
        今天: [] as Conversation[],
        三天内: [] as Conversation[],
        七天内: [] as Conversation[],
        三十天内: [] as Conversation[],
        更早: [] as Conversation[],
      }
      const today = dayjs().startOf('day')
      const tday = dayjs().subtract(3, 'day')
      const sday = dayjs().subtract(7, 'day')
      const mday = dayjs().subtract(30, 'day')
      for (const item of state.conversationList) {
        const date = dayjs(item.updated_at)
        if (date.isSameOrAfter(today)) {
          result.今天.push(item)
        } else if (date.isSameOrAfter(tday)) {
          result.三天内.push(item)
        } else if (date.isSameOrAfter(sday)) {
          result.七天内.push(item)
        } else if (date.isSameOrAfter(mday)) {
          result.三十天内.push(item)
        } else {
          result.更早.push(item)
        }
      }
      for (const key in result) {
        if (!result[key].length) {
          delete result[key]
        }
      }
      return result
    },
    getCurrent: (state): Conversation | undefined => {
      return state.conversationList.find((item) => item.key === state.currentKey)
    },
    isNew() {
      if (!this.getCurrent) {
        return false
      }
      return (
        (this.getCurrent as unknown as Conversation).id !==
        (this.getCurrent as unknown as Conversation).key
      )
    },
  },
  actions: {
    setConversationId(id: string) {
      const index = this.conversationList.findIndex((item) => item.key === this.currentKey)
      const conversation = this.conversationList[index]
      this.conversationList.splice(index, 1, { ...conversation, id })
    },
    async renameConversation(key: string, name: string) {
      try {
        const current = this.getCurrent
        if (current?.id) {
          const userStore = useUserStore()
          await renameConversation(current.id, name, userStore.userName)
        }
        const index = this.conversationList.findIndex((item) => item.key === key)
        const conversation = this.conversationList[index]
        this.conversationList.splice(index, 1, { ...conversation, name })
      } catch (error) {
        console.error('重命名会话错误: ', error)
      }
    },
    async deleteConversation(key: string) {
      try {
        const current = this.getCurrent
        if (current?.id) {
          const userStore = useUserStore()
          await deleteConversation(current.id, userStore.userName)
        }
        const index = this.conversationList.findIndex((item) => item.key === key)
        this.conversationList.splice(index, 1)
      } catch (error) {
        console.error('删除会话错误: ', error)
      }
    },
    async getConversationMessages() {
      try {
        const current = this.getCurrent
        if (!current?.id) {
          return
        }
        const userStore = useUserStore()
        const res = await getConversationById({
          conversation_id: current.id,
          user: userStore.userName,
          first_id: this.messageFirstId,
        })
        if (res) {
          const list = res.data || []
          this.messageHasMore = !!res.has_more
          this.messageFirstId = list.length ? (list[0].id as string) : ''
        }
        return res
      } catch (error) {
        console.error('请求会话历史错误: ', error)
      }
    },
    async getConversationList() {
      this.loading = true
      try {
        const userStore = useUserStore()
        const res = await getConversationList({
          pinned: false,
          user: userStore.userName,
          last_id: this.lastId,
        })
        if (res) {
          const list: Conversation[] = res.data || []
          this.conversationList.push(
            ...list.map((item) => ({
              ...item,
              key: item.id as string,
              created_at: item.created_at * 1000,
              updated_at: item.updated_at * 1000,
            })),
          )
          this.hasMore = !!res.has_more
          this.lastId = this.conversationList.length
            ? (this.conversationList[this.conversationList.length - 1].id as string)
            : ''
        }
      } catch (error) {
        console.error('加载会话列表错误:', error)
      } finally {
        this.loading = false
      }
    },
    addConversation(conversation: Conversation) {
      this.conversationList.unshift(conversation)
    },
  },
})
